﻿using BtLabelTool;
using HandyControl.Controls;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Controls;
using System.Windows.Media;
using WebSocket4Net;

namespace 刷屏测试软件.BLL
{
    public class TestViewBLL
    {
        private readonly object recievelock = new object();
        private BtLabelDAL.RefreshDAL refreshDAL = new BtLabelDAL.RefreshDAL();
        private BtLabelDAL.HttpDAL httpDAL = new BtLabelDAL.HttpDAL();
        private WebSocket4Net.WebSocket webSocket4Net = null;
        private ListBox _listBox = new ListBox();
        private ViewModel.TestViewModel _testViewModel = null;
        private string ser_id;
        public TestViewBLL(ListBox listBox, ViewModel.TestViewModel testViewModel)
        {
            try
            {
                var dic = ConfigHelper.ReadAll();
                string SocketUrl = dic["SocketUrl"];
                _listBox = listBox;
                _testViewModel = testViewModel;
                ser_id = CommonHelper.GetTimeStamp().ToString().Substring(0, 10);
                string socketUrl = SocketUrl + ser_id;
                webSocket4Net = new WebSocket4Net.WebSocket(socketUrl);
                webSocket4Net.MessageReceived += WebSocket4Net_MessageReceived;
                webSocket4Net.Open();
            }
            catch (Exception ex)
            {
                throw ex;
            }

        }

        private void WebSocket4Net_MessageReceived(object sender, MessageReceivedEventArgs e)
        {
            try
            {
                lock (recievelock)
                {
                    if (e.Message.Contains("des"))
                    {
                        var refreshLabelRb = JsonConvert.DeserializeObject<BtLabelModel.HttpModel.RefreshLabelRb>(e.Message);

                        var item = _testViewModel.MacItems.Where(it => it.Mac == refreshLabelRb.mac.Trim()).FirstOrDefault();
                        if (item != null)
                        {
                            _listBox.Dispatcher.Invoke(() =>
                            {
                                if (refreshLabelRb.des == "点灯成功")
                                {
                                    item.LightResult = refreshLabelRb.des;
                                    if (item.RefreshResult == "设备刷新成功")
                                    {
                                        var model = new BtLabelModel.RefreshDbModel.Refresh_Table()
                                        {
                                            mac = item.Mac,
                                            dbm = item.dBm,
                                            battery = item.Battery,
                                            ver = item.Ver,
                                            time = DateTime.Now
                                        };
                                        if (refreshDAL.Update(model) == false)
                                        {
                                            item.RefreshResult = "数据上传失败";
                                            item.BackColor = Brushes.Tomato;
                                            InitCount();
                                            return;
                                        }
                                        if (View.TestView.selecting)
                                        {
                                            item.ItemHeight = 0;
                                        }
                                        else
                                        {
                                            item.ItemHeight = 40;
                                        }
                                        item.IsCheck = false;
                                        item.BackColor = Brushes.YellowGreen;
                                        InitCount();
                                    }
                                }
                                //todo:
                                else if (refreshLabelRb.des == "设备刷新成功")
                                {
                                    item.RefreshResult = refreshLabelRb.des;
                                    if (item.LightResult == "点灯成功")
                                    {
                                        var model = new BtLabelModel.RefreshDbModel.Refresh_Table()
                                        {
                                            mac = item.Mac,
                                            dbm = item.dBm,
                                            battery = item.Battery,
                                            ver = item.Ver,
                                            time = DateTime.Now
                                        };
                                        if (refreshDAL.Update(model) == false)
                                        {
                                            item.RefreshResult = "数据上传失败";
                                            item.BackColor = Brushes.Tomato;
                                            InitCount();
                                            return;
                                        }
                                        if (View.TestView.selecting)
                                        {
                                            item.ItemHeight = 0;
                                        }
                                        else
                                        {
                                            item.ItemHeight = 40;
                                        }
                                        item.IsCheck = false;
                                        item.BackColor = Brushes.YellowGreen;
                                        InitCount();
                                    }
                                }
                                //todo
                                else if (refreshLabelRb.des == "设备刷新失败")
                                {
                                    item.RefreshResult = refreshLabelRb.des;
                                    item.BackColor = Brushes.Tomato;
                                    InitCount();
                                }
                                //todo
                                else
                                {
                                    item.LightResult = refreshLabelRb.des;
                                    item.BackColor = Brushes.Tomato;
                                    InitCount();
                                }
                            });
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Growl.Warning(ex.Message);
            }

        }

        public void LightLed(ViewModel.TestViewModel.Item item)
        {
            try
            {
                List<string> macs = new List<string>();
                macs.Add(item.Mac);
                _listBox.Dispatcher.Invoke(() =>
                {
                    if (item.BackColor != Brushes.Tomato)
                    {
                        item.BackColor = Brushes.Gold;
                    }
                    item.LightResult = "发送命令";
                    InitCount();
                });
                if (webSocket4Net.State != WebSocket4Net.WebSocketState.Open)
                {
                    ser_id = CommonHelper.GetTimeStamp().ToString().Substring(0, 10);
                    var dic = ConfigHelper.ReadAll();
                    string SocketUrl = dic["SocketUrl"];
                    string socketUrl = SocketUrl + ser_id;
                    webSocket4Net = new WebSocket4Net.WebSocket(socketUrl);
                    webSocket4Net.MessageReceived += WebSocket4Net_MessageReceived;
                    webSocket4Net.Open();
                }
                BtLabelModel.HttpModel.LightLedDto dto = new BtLabelModel.HttpModel.LightLedDto();
                dto.mac = JsonConvert.SerializeObject(macs.ToArray());
                dto.ser_id = ser_id;
                dto.mode = "0";
                dto.time = "100";
                dto.otime = "0";
                dto.cycle = "0";
                dto.color = "00FF00";
                string str = JsonConvert.SerializeObject(dto);
                ArraySegment<byte> bytesToSend = new ArraySegment<byte>(Encoding.UTF8.GetBytes(str));
                bool isPost = httpDAL.HttpPostLed(dto);
                _listBox.Dispatcher.Invoke(() =>
                {
                    if (isPost == false)
                    {
                        item.BackColor = Brushes.Tomato;
                        item.LightResult = "发送失败";
                        InitCount();
                        return;
                    }
                    else
                    {
                        item.LightResult = "发送完成";
                    }
                });
            }
            catch (Exception ex)
            {
                _listBox.Dispatcher.Invoke(() =>
                {
                    item.BackColor = Brushes.Tomato;
                    item.LightResult = "发送失败";
                    InitCount();
                });
                throw ex;
            }

        }

        public void RefreshPic(ViewModel.TestViewModel.Item item)
        {
            try
            {
                List<string> macs = new List<string>();
                macs.Add(item.Mac);
                _listBox.Dispatcher.Invoke(() =>
                {
                    if (item.BackColor != Brushes.Tomato)
                    {
                        item.BackColor = Brushes.Gold;
                    }
                    item.RefreshResult = "发送命令";
                    InitCount();
                });
                if (webSocket4Net.State != WebSocket4Net.WebSocketState.Open)
                {
                    ser_id = CommonHelper.GetTimeStamp().ToString().Substring(0, 10);
                    var dic = ConfigHelper.ReadAll();
                    string SocketUrl = dic["SocketUrl"];
                    string socketUrl = SocketUrl + ser_id;
                    webSocket4Net = new WebSocket4Net.WebSocket(socketUrl);
                    webSocket4Net.MessageReceived += WebSocket4Net_MessageReceived;
                    webSocket4Net.Open();
                }
                BtLabelModel.HttpModel.RefreshLabelDto dto = new BtLabelModel.HttpModel.RefreshLabelDto();
                dto.mac = JsonConvert.SerializeObject(macs.ToArray());
                dto.ser_id = ser_id;
                dto.msg = "";
                string str = JsonConvert.SerializeObject(dto);
                ArraySegment<byte> bytesToSend = new ArraySegment<byte>(Encoding.UTF8.GetBytes(str));
                bool isPost = httpDAL.HttpPostRefresh(dto);
                _listBox.Dispatcher.Invoke(() =>
                {
                    if (isPost == false)
                    {
                        item.BackColor = Brushes.Tomato;
                        item.RefreshResult = "发送失败";
                        InitCount();
                    }
                    else
                    {
                        item.RefreshResult = "发送完成";
                    }
                });
            }
            catch (Exception ex)
            {
                _listBox.Dispatcher.Invoke(() =>
                {
                    item.BackColor = Brushes.Tomato;
                    item.RefreshResult = "发送失败";
                    InitCount();
                });
                throw ex;
            }

        }
        public void LightLeds(List<ViewModel.TestViewModel.Item> items)
        {
            try
            {
                List<string> macs = new List<string>();
                foreach (var item in items)
                {
                    if (item.IsCheck)
                    {
                        macs.Add(item.Mac);
                        _listBox.Dispatcher.Invoke(() =>
                        {
                            if (item.BackColor != Brushes.Tomato)
                            {
                                item.BackColor = Brushes.Gold;
                            }
                            item.LightResult = "发送命令";
                        });
                    }
                }
                _listBox.Dispatcher.Invoke(() =>
                {
                    InitCount();
                });
                if (webSocket4Net.State != WebSocket4Net.WebSocketState.Open)
                {
                    ser_id = CommonHelper.GetTimeStamp().ToString().Substring(0, 10);
                    var dic = ConfigHelper.ReadAll();
                    string SocketUrl = dic["SocketUrl"];
                    string socketUrl = SocketUrl + ser_id;
                    webSocket4Net = new WebSocket4Net.WebSocket(socketUrl);
                    webSocket4Net.MessageReceived += WebSocket4Net_MessageReceived;
                    webSocket4Net.Open();
                }
                BtLabelModel.HttpModel.LightLedDto dto = new BtLabelModel.HttpModel.LightLedDto();
                dto.mac = JsonConvert.SerializeObject(macs.ToArray());
                dto.ser_id = ser_id;
                dto.mode = "0";
                dto.time = "100";
                dto.otime = "0";
                dto.cycle = "0";
                dto.color = "00FF00";
                string str = JsonConvert.SerializeObject(dto);
                ArraySegment<byte> bytesToSend = new ArraySegment<byte>(Encoding.UTF8.GetBytes(str));
                bool isPost = httpDAL.HttpPostLed(dto);
                foreach (var item in items)
                {
                    if (item.IsCheck)
                    {
                        _listBox.Dispatcher.Invoke(() =>
                        {
                            if (isPost == false)
                            {
                                item.BackColor = Brushes.Tomato;
                                item.LightResult = "发送失败";
                            }
                            else
                            {
                                item.LightResult = "发送完成";
                            }
                        });
                    }
                }
                _listBox.Dispatcher.Invoke(() =>
                {
                    InitCount();
                });
            }
            catch (Exception ex)
            {
                foreach (var item in items)
                {
                    if (item.IsCheck)
                    {
                        _listBox.Dispatcher.Invoke(() =>
                        {
                            item.BackColor = Brushes.Tomato;
                            item.LightResult = "发送失败";
                        });
                    }
                }
                _listBox.Dispatcher.Invoke(() =>
                {
                    InitCount();
                });
                throw ex;
            }
        }
        public void RefreshPics(List<ViewModel.TestViewModel.Item> items)
        {
            try
            {
                List<string> macs = new List<string>();
                foreach (var item in items)
                {
                    if (item.IsCheck && item.BackColor == Brushes.Gold)
                    {
                        macs.Add(item.Mac);
                        _listBox.Dispatcher.Invoke(() =>
                        {
                            if (item.BackColor != Brushes.Tomato)
                            {
                                item.BackColor = Brushes.Gold;
                            }
                            item.RefreshResult = "发送命令";
                        });
                    }
                }
                _listBox.Dispatcher.Invoke(() =>
                {
                    InitCount();
                });
                if (webSocket4Net.State != WebSocket4Net.WebSocketState.Open)
                {
                    ser_id = CommonHelper.GetTimeStamp().ToString().Substring(0, 10);
                    var dic = ConfigHelper.ReadAll();
                    string SocketUrl = dic["SocketUrl"];
                    string socketUrl = SocketUrl + ser_id;
                    webSocket4Net = new WebSocket4Net.WebSocket(socketUrl);
                    webSocket4Net.MessageReceived += WebSocket4Net_MessageReceived;
                    webSocket4Net.Open();
                }
                BtLabelModel.HttpModel.RefreshLabelDto dto = new BtLabelModel.HttpModel.RefreshLabelDto();
                dto.mac = JsonConvert.SerializeObject(macs.ToArray());
                dto.ser_id = ser_id;
                dto.msg = "";
                string str = JsonConvert.SerializeObject(dto);
                ArraySegment<byte> bytesToSend = new ArraySegment<byte>(Encoding.UTF8.GetBytes(str));
                bool isPost = httpDAL.HttpPostRefresh(dto);
                foreach (var item in items)
                {
                    if (item.IsCheck)
                    {
                        _listBox.Dispatcher.Invoke(() =>
                        {
                            if (isPost == false)
                            {
                                item.BackColor = Brushes.Tomato;
                                item.RefreshResult = "发送失败";
                            }
                            else
                            {
                                item.RefreshResult = "发送完成";
                            }
                        });
                    }
                }
                _listBox.Dispatcher.Invoke(() =>
                {
                    InitCount();
                });
            }
            catch (Exception ex)
            {
                foreach (var item in items)
                {
                    if (item.IsCheck)
                    {
                        _listBox.Dispatcher.Invoke(() =>
                        {
                            item.BackColor = Brushes.Tomato;
                            item.RefreshResult = "发送失败";
                        });
                    }
                }
                _listBox.Dispatcher.Invoke(() =>
                {
                    InitCount();
                });
                throw ex;
            }

        }
        private void InitCount()
        {
            int ing = 0;
            int pass = 0;
            int fail = 0;
            int wait = 0;
            foreach (var item in _testViewModel.MacItems)
            {
                if (item.BackColor == Brushes.LightGray)
                {
                    wait++;
                }
                if (item.BackColor == Brushes.Gold)
                {
                    ing++;
                }
                if (item.BackColor == Brushes.YellowGreen)
                {
                    pass++;
                }
                if (item.BackColor == Brushes.Tomato)
                {
                    fail++;
                }
            }
            _testViewModel.AllCount = wait + ing + pass + fail;
            _testViewModel.WaitCount = wait;
            _testViewModel.IngCount = ing;
            _testViewModel.PassCount = pass;
            _testViewModel.FailCount = fail;
        }
    
        public void CloseSocket()
        {
            try
            {
                if (webSocket4Net.State == WebSocket4Net.WebSocketState.Open)
                {
                    webSocket4Net.Close();
                    webSocket4Net.Dispose();
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }

        }
    }
}
